package com.ls.rbac.security;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * created by liush on 2025/6/27
 **/
@Component
public class ConcurrentSessionExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        HttpServletResponse response = event.getResponse();
        response.setContentType("application/json;charset=UTF-8");
        String jsonString = JSON.toJSONString(new AuthenticationResult(0, HttpStatus.UNAUTHORIZED.value(), "当前账号已在其他设备上登录", null, null));
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.close();
    }
}
